package com.nl.lib_project.view.dialog

import android.annotation.SuppressLint
import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.Html
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.CallSuper
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat.getSystemService
import androidx.core.content.FileProvider
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.github.gzuliyujiang.dialog.DialogLog
import com.github.gzuliyujiang.dialog.ModalDialog
import com.hjq.http.EasyHttp
import com.hjq.http.listener.OnDownloadListener
import com.hjq.http.model.HttpMethod
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.nl.lib_core.tool.extends.visible
import com.nl.lib_project.BuildConfig
import com.nl.lib_project.R
import com.nl.lib_project.view.textview.DownloadProgressView
import java.io.File

/** 作者: wangfei 创建时间: 2021/10/15 包名: com.nl.lib_project.view.dialog 类名: UpdateDialog */
class UpdateDialog(activity: Activity, private var lifecycleOwner: LifecycleOwner) :
    ModalDialog(activity) {

  private var mTvContent: TextView? = null

  private var mTvVersionCode: TextView? = null

  private var mLifecycle: LifecycleRegistry? = null
  /** 当前是否下载中 */
  private var mDownloading = false
  /** 当前是否下载完毕 */
  private var mDownloadComplete = false
  /** Apk 文件 */
  private var mApkFile: File? = null

  /** 是否强制更新 */
  private var mForceUpdate = false

  private var mTvUpDownLoad: TextView? = null

  private var mDownProgressLoad: DownloadProgressView? = null

  private var mIvCancel: ImageView? = null

  /** 下载地址 */
  private var mDownloadUrl: String? = null

  override fun createHeaderView(): View {
    return View.inflate(activity, R.layout.dialog_header_style_4, null)
  }

  override fun createTopLineView(): View? {
    return null
  }

  override fun onInit(savedInstanceState: Bundle?) {
    super.onInit(savedInstanceState)
    setCanceledOnTouchOutside(false)
    setCancelable(false)
  }

  override fun createBodyView(): View {
    return View.inflate(activity, R.layout.project_update_dialog, null)
  }

  override fun createFooterView(): View? {
    return null
  }

  override fun initView() {
    mLifecycle = LifecycleRegistry(lifecycleOwner)
    super.initView()
    mTvContent = findViewById(R.id.tv_content)
    mDownProgressLoad = findViewById(R.id.down_progress_load)
    mTvVersionCode = findViewById(R.id.tv_version_code)
    mTvUpDownLoad = findViewById(R.id.tv_up_down_load)
    mIvCancel = findViewById(R.id.iv_cancel)
    mTvUpDownLoad?.setOnClickListener(this)
    mIvCancel?.setOnClickListener(this)
  }

  fun setUpDateContent(value: String) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      mTvContent?.text = Html.fromHtml(value, Html.FROM_HTML_MODE_LEGACY)
    } else {
      mTvContent?.text = Html.fromHtml(value)
    }
  }

  fun setVersionCode(value: String) {
    mTvVersionCode?.text = value
  }

  @SuppressLint("MissingSuperCall")
  @CallSuper
  override fun onClick(v: View) {
    val id = v.id
    if (id == R.id.iv_cancel) {
      DialogLog.print("cancel clicked")
      onCancel()
      dismiss()
    } else if (id == R.id.tv_up_down_load) {
      DialogLog.print("ok clicked")
      onOk()
    }
  }

  override fun onCancel() {}

  override fun onOk() {
    // 判断下载状态
    if (mDownloadComplete) {
      if (mApkFile!!.isFile) {
        // 下载完毕，安装 Apk
        installApk()
        dismiss()
      } else {
        // 下载失败，重新下载
        downloadApk()
      }
    } else if (!mDownloading) {
      // 没有下载，开启下载
      downloadApk()
    }
  }

  private fun downloadApk() {
    XXPermissions.with(context)
        .permission(listOf(Permission.MANAGE_EXTERNAL_STORAGE, Permission.REQUEST_INSTALL_PACKAGES))
        .request { permissions, all ->
          val notificationManager: NotificationManager =
              getSystemService(context, NotificationManager::class.java)!!
          val notificationId = context.applicationInfo.uid
          var channelId = ""
          // 适配 Android 8.0 通知渠道新特性
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel =
                NotificationChannel(
                    context.getString(R.string.update_notification_channel_id),
                    context.getString(R.string.update_notification_channel_name),
                    NotificationManager.IMPORTANCE_LOW)
            channel.enableLights(false)
            channel.enableVibration(false)
            channel.vibrationPattern = longArrayOf(0)
            channel.setSound(null, null)
            notificationManager.createNotificationChannel(channel)
            channelId = channel.id
          }
          val notificationBuilder: NotificationCompat.Builder =
              NotificationCompat.Builder(context, channelId) // 设置通知时间
                  .setWhen(System.currentTimeMillis()) // 设置通知标题
                  .setContentTitle(context.getString(R.string.app_name)) // 设置通知小图标
                  .setSmallIcon(R.mipmap.ic_launcher) // 设置通知大图标
                  .setLargeIcon(
                      BitmapFactory.decodeResource(
                          context.resources, R.mipmap.ic_launcher)) // 设置通知静音
                  .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE) // 设置震动频率
                  .setVibrate(longArrayOf(0)) // 设置声音文件
                  .setSound(null) // 设置通知的优先级
                  .setPriority(NotificationCompat.PRIORITY_DEFAULT)
          // 创建要下载的文件对象
          mApkFile =
              File(
                  context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS),
                  context.getString(R.string.app_name) +
                      "_v_" +
                      mTvVersionCode?.text.toString() +
                      ".apk")
          EasyHttp.download(lifecycleOwner)
              .method(HttpMethod.GET)
              .file(mApkFile)
              .url(mDownloadUrl)
              .listener(
                  object : OnDownloadListener {
                    override fun onStart(file: File) {
                      // 标记为下载中
                      mDownloading = true
                      // 标记成未下载完成
                      mDownloadComplete = false
                      // 后台更新
                      mIvCancel?.visibility = View.GONE
                      // 隐藏更新按钮
                      mTvUpDownLoad?.visibility = View.GONE
                      // 显示进度条
                      mDownProgressLoad?.visibility = View.VISIBLE
                    }
                    override fun onProgress(file: File, progress: Int) {
                      mDownProgressLoad?.currentProgress(progress)
                      // 更新下载通知
                      notificationManager.notify(
                          notificationId,
                          notificationBuilder // 设置通知的文本
                              .setContentText(
                                  java.lang.String.format(
                                      context.getString(R.string.update_status_running),
                                      progress)) // 设置下载的进度
                              .setProgress(100, progress, false) // 设置点击通知后是否自动消失
                              .setAutoCancel(false) // 是否正在交互中
                              .setOngoing(true) // 重新创建新的通知对象
                              .build())
                    }

                    @SuppressLint("StringFormatInvalid")
                    override fun onComplete(file: File) {
                      // 显示下载成功通知
                      notificationManager.notify(
                          notificationId,
                          notificationBuilder // 设置通知的文本
                              .setContentText(
                                  java.lang.String.format(
                                      context.getString(R.string.update_status_successful),
                                      100)) // 设置下载的进度
                              .setProgress(100, 100, false) // 设置通知点击之后的意图
                              .setContentIntent(
                                  PendingIntent.getActivity(
                                      context,
                                      1,
                                      getInstallIntent(),
                                      Intent.FILL_IN_ACTION)) // 设置点击通知后是否自动消失
                              .setAutoCancel(true) // 是否正在交互中
                              .setOngoing(false)
                              .build())
                      mTvUpDownLoad?.visibility = View.VISIBLE
                      mTvUpDownLoad?.text = context.getString(R.string.install)
                      mDownProgressLoad?.visibility = View.GONE
                      // 标记成下载完成
                      mDownloadComplete = true
                      //                      // 安装 Apk
                    }
                    override fun onError(file: File, e: Exception) {
                      // 清除通知
                      notificationManager.cancel(notificationId)
                      // 删除下载的文件
                      file.delete()
                      /** 下载失败的时候可以选择关闭或者重新下载 */
                      mTvUpDownLoad?.text = "下载失败,重新下载"
                      mTvUpDownLoad?.visible()
                      mIvCancel?.visible()
                    }
                    override fun onEnd(file: File) {
                      // 更新进度条
                      mDownProgressLoad?.visibility = View.GONE

                      // 标记当前不是下载中
                      mDownloading = false
                      // 如果当前不是强制更新，对话框就恢复成可取消状态
                      if (!mForceUpdate) {
                        setCancelable(true)
                      }
                      // dismiss()
                    }
                  })
              .start()
        }
  }

  private fun installApk() {
    XXPermissions.with(context).permission(Permission.REQUEST_INSTALL_PACKAGES).request { _, _ ->
      context.startActivity(getInstallIntent())
    }
  }

  /** 获取安装意图 */
  private fun getInstallIntent(): Intent {
    val intent = Intent()
    intent.action = Intent.ACTION_VIEW
    val uri: Uri
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
      uri = FileProvider.getUriForFile(context, BuildConfig.applicationId + ".provider", mApkFile!!)
      intent.addFlags(
          Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
    } else {
      uri = Uri.fromFile(mApkFile)
    }
    intent.setDataAndType(uri, "application/vnd.android.package-archive")
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    return intent
  }

  /** 设置强制更新 */
  fun setForceUpdate(force: Boolean) {
    mForceUpdate = force
    mIvCancel!!.visibility = if (force) View.GONE else View.VISIBLE
    setCancelable(!force)
  }

  /** 设置下载 url */
  fun setDownloadUrl(url: String) {
    mDownloadUrl = url
  }
}
